//
//  NoViewBaseTable.m
//  OperationPro
//
//  Created by yaxue wang on 16/10/13.
//  Copyright © 2016年 展鸿科技. All rights reserved.
//

#import "NoViewBaseTable.h"
#import "CBaseTableCell.h"
#import "DataModel.h"
#import "SVPullToRefresh.h"
//#import "LoadingView.h"
#import "NoDataView.h"
@interface NoViewBaseTable()
@property (nonatomic, strong) Class cellClass;
@property (nonatomic, strong) Class model;

@property (nonatomic) NSInteger currentPage;
@property (nonatomic) NSInteger perPCount;
@property (nonatomic, strong) NSString *baseUrl;
@property (nonatomic, strong) NSDictionary *apiParam;
@property (nonatomic, strong)NoDataView *NoDataView;
@property (nonatomic) BOOL hasMoreData;

@property (nonatomic) BOOL isfirstshow;


@end

@implementation NoViewBaseTable

- (instancetype)initWithFrame:(CGRect)frame style:(UITableViewStyle)style{
    self = [super initWithFrame:frame style:style];
    if (self) {
        [self initData];
        self.backgroundColor =[UIColor clearColor];
        [self initView];
    }
    return self;
}

- (void)loadData{
    _isfirstshow = false;
    if (_baseUrl == nil || [_baseUrl isEqualToString:@""]) {
        return;
    }
    if (_model == nil) {
        
    }
    
    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:_apiParam ? _apiParam : @{}];

        [dic setObject:[NSString stringWithFormat:@"%zd", _currentPage] forKey:@"pageNumber"];
        [dic setObject:[NSString stringWithFormat:@"%zd", _perPCount] forKey:@"pageSize"];
    
    //    NSAssert(_model == nil, @"未初始化Model类型");
    [CClass HttpRequestTask:NO withUrl:_baseUrl withData:dic notifyError:NO onSuccess:^(BaseModel *model) {
        DataModel *data;
        NSMutableArray *list;
        if ([model.B_data isKindOfClass:[NSDictionary class]]) {
            data = [[DataModel alloc] initWithDictionary:model.B_data error:nil];
            self.hasMoreData = [data.D_totalPage integerValue] != _currentPage;
            list = [_model arrayOfModelsFromDictionaries:(NSArray *)data.D_list error:nil];
            self.infiniteScrollingView.enabled = YES;
        }else{
            list = [_model arrayOfModelsFromDictionaries:(NSArray *)model.B_data error:nil];
        }
        self.extData = data;
        if (_currentPage == 1) {
            self.mainData = list;
            [self.pullToRefreshView stopAnimating];
            self.pullToRefreshView.textColor =[UIColor grayColor];
            self.pullToRefreshView.arrowColor =[UIColor grayColor];
        }else{
            [self.mainData addObjectsFromArray:list];
            [self.infiniteScrollingView stopAnimating];
        }
        if (self.showNoData) {
            [self.NoDataView setHidden:self.mainData.count != 0];
            [self setScrollEnabled:self.mainData.count != 0];
        }
        if([data.D_pageNumber isEqualToString:data.D_totalPage] || list.count < _perPCount){
            self.infiniteScrollingView.enabled = NO;
        }
        
        [self reloadData];
    } onError:^(BaseModel *model) {
        
    }];
}

- (id) getRowData:(NSIndexPath *)indexPath{
    return [self numberOfSections] > 1 || self.needSection ? self.mainData[indexPath.section][indexPath.row] : self.mainData[indexPath.row];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [tableView numberOfSections] > 1 || self.needSection ? [self.mainData[section] count] : self.mainData.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    Class class = _cellClass;
    if (class == nil) {
        class = [CBaseTableCell class];
    }
    return [class getCellHeightByModel:[self getRowData:indexPath]];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    Class class = _cellClass;
    if (class == nil) {
        class = [CBaseTableCell class];
    }
    NSString *cellID = [NSString stringWithFormat:@"Cell_%@", NSStringFromClass(class)];
    CBaseTableCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (cell == nil) {
        cell = [[class alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
    }
    if (self.mainData.count == 0) {
        [cell setModel:nil];
        return cell;
    }
    [cell setModel:[self getRowData:indexPath]];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (self.CCellSelect) {
        if (self.mainData.count == 0) {
            self.CCellSelect(nil);
            return;
        }
        self.CCellSelect([self getRowData:indexPath]);
    }
}

- (void)initData{
    self.mainData = [NSMutableArray array];
    _currentPage = 1;
    _perPCount = 10;
    _hasMoreData = false;
    _isfirstshow = YES;
    self.showNoData = YES;
}

- (void)setPerPageCount:(NSInteger)perPageCount{
    _perPageCount = perPageCount;
    _perPCount = perPageCount;
}

- (void) setDataWithUrl:(NSString *)url andParam:(NSDictionary *)dic{
    _baseUrl = url;
    _apiParam = dic;
}

- (void)viewAppear{
    if (_isfirstshow) {
        [self refresh];
    }
}

- (void)initView{
    [self setDelegate:self];
    [self setDataSource:self];
}


- (void) refresh{
    _currentPage = 1;
    [self loadData];
}

- (void) addRefresh{
    __block typeof(self) superself = self;
    [self addPullToRefreshWithActionHandler:^{
        [superself.infiniteScrollingView stopAnimating];
        [superself refresh];
    }];
}

- (void) addMore{
    __block typeof(self) superself = self;
    [self addInfiniteScrollingWithActionHandler:^{
        if (_hasMoreData == false) {
            [superself.infiniteScrollingView stopAnimating];
            [superself refresh];
            return ;
        }
        _currentPage += 1;
        [superself.pullToRefreshView stopAnimating];
        [superself loadData];
    }];
}

- (void) registerCell:(Class) cellClass withModel:(Class)model{
    _cellClass = cellClass;
    _model = model;
}


@end
